#include "tju_tcp.h"
#include <signal.h>
#include <math.h>

// 调试输出文件指针已在kernel.c中定义，这里使用extern声明

// 设置调试输出文件
void set_debug_log_file(const char* filename) {
    // 如果已经打开了文件，先关闭
    if (debug_log_file != NULL) {
        fclose(debug_log_file);
        debug_log_file = NULL;
    }
    
    // 打开新文件
    if (filename != NULL) {
        debug_log_file = fopen(filename, "w");
        if (debug_log_file == NULL) {
            fprintf(stderr, "无法打开调试日志文件: %s\n", filename);
        } else {
            fprintf(debug_log_file, "=== 调试日志开始 ===\n");
            fflush(debug_log_file);
        }
    }
}

// 关闭调试输出文件
void close_debug_log_file() {
    if (debug_log_file != NULL) {
        fprintf(debug_log_file, "=== 调试日志结束 ===\n");
        fclose(debug_log_file);
        debug_log_file = NULL;
    }
}

// 状态字符串数组，用于调试输出
static const char* state_str[] = {
    "CLOSED", "LISTEN", "SYN_SENT", "SYN_RECV", "ESTABLISHED",
    "FIN_WAIT_1", "FIN_WAIT_2", "CLOSE_WAIT", "CLOSING", "LAST_ACK", "TIME_WAIT"
};

//全局的curr_sock指针，用于在计时器处理函数中访问当前socket
tju_tcp_t* curr_sock = NULL;

/*
循环队列结构定义
*/
typedef struct {
    tju_tcp_t* queue[MAX_SOCK];  // 队列数组
    int front;                   // 队头指针
    int rear;                    // 队尾指针
    int count;                   // 当前队列元素数量
} tcp_circular_queue_t;

/*
半连接与全连接循环队列
由于只有一个listen socket，简化实现
*/
tcp_circular_queue_t syn_queue;
tcp_circular_queue_t established_queue;

pthread_mutex_t syn_queue_lock;
pthread_mutex_t established_queue_lock;
pthread_cond_t syn_queue_not_empty;
pthread_cond_t established_queue_not_empty;

//辅助函数声明
//全连接、半连接队列操作相关
static int syn_queue_enqueue(tju_tcp_t* sock);
static tju_tcp_t* syn_queue_dequeue();
static int syn_queue_is_empty();
static int established_queue_enqueue(tju_tcp_t* sock);
static tju_tcp_t* established_queue_dequeue();
static int established_queue_is_empty();
//未确认数据包链表相关
static void add_nacked_packet(tju_tcp_t* sock, tju_packet_t* pkt);
static void remove_nacked_packet(tju_tcp_t* sock, uint32_t ack_seq);
//已接收数据包链表相关
static void add_received_packet(tju_tcp_t* sock, uint32_t seq, uint16_t len, char* data);
static void remove_received_packet(tju_tcp_t* sock, uint32_t seq);
static void retransmit_nacked_packets(tju_tcp_t* sock);
//计时器相关
static void timeout_handler(int signum);
static void start_timer(tju_tcp_t* sock);
static void stop_timer(tju_tcp_t* sock);
static void reset_timer(tju_tcp_t* sock);
// 发送包相关
static void send_ack(tju_tcp_t* sock, struct timeval sent_time);



/*
创建 TCP socket 
初始化对应的结构体
设置初始状态为 CLOSED
*/
tju_tcp_t* tju_socket(){
    tju_tcp_t* sock = (tju_tcp_t*)malloc(sizeof(tju_tcp_t));
    sock->state = CLOSED;
    pthread_mutex_init(&(sock->state_lock), NULL);
    pthread_cond_init(&(sock->wait_cond), NULL);
    
    pthread_mutex_init(&(sock->send_lock), NULL);
    sock->sending_buf = NULL;
    sock->sending_len = 0;

    pthread_mutex_init(&(sock->recv_lock), NULL);
    sock->received_buf = NULL;
    sock->received_len = 0;
    
    if(pthread_cond_init(&sock->wait_cond, NULL) != 0){
        perror("ERROR condition variable not set\n");
        exit(-1);
    }

    sock->window.wnd_send = malloc(sizeof(sender_window_t));
    sock->window.wnd_send->window_size = TCP_RECVWN_SIZE;
    pthread_cond_init(&(sock->window.wnd_send->send_window_not_full), NULL);
    pthread_cond_init(&(sock->window.wnd_send->recv_window_not_full), NULL);
    sock->window.wnd_send->base = 0;
    sock->window.wnd_send->nextseq = 0;
    sock->window.wnd_send->rwnd = TCP_RECVWN_SIZE;
    sock->window.wnd_send->estimated_rtt = 0;
    sock->window.wnd_send->dev_rtt = 0;
    sock->window.wnd_send->ack_cnt = 0;
    reset_timer(sock);
    sock->window.wnd_send->timeout.it_interval.tv_sec = 0;
    sock->window.wnd_send->timeout.it_interval.tv_usec = 0;
    sock->window.wnd_send->head = NULL;
    sock->window.wnd_send->congestion_status = SLOW_START;
    sock->window.wnd_send->cwnd = MAX_DLEN;
    sock->window.wnd_send->ssthresh = 16 * MAX_DLEN;
    sock->window.wnd_send->window_size = sock->window.wnd_send->rwnd < sock->window.wnd_send->cwnd ? sock->window.wnd_send->rwnd : sock->window.wnd_send->cwnd;
    
    sock->window.wnd_recv = malloc(sizeof(receiver_window_t));
    sock->window.wnd_recv->expect_seq = 0;
    sock->window.wnd_recv->head = NULL;
    sock->window.wnd_recv->window_size = TCP_RECVWN_SIZE;
    
    return sock;
}

/*
绑定监听的地址 包括ip和端口
*/
int tju_bind(tju_tcp_t* sock, tju_sock_addr bind_addr){
    sock->bind_addr = bind_addr;
    return 0;
}

/*
被动打开 监听bind的地址和端口
设置socket的状态为LISTEN
注册该socket到内核的监听socket哈希表
*/
int tju_listen(tju_tcp_t* sock){
    sock->state = LISTEN;
    DEBUG_STATE("Socket %p 进入LISTEN状态，绑定到 %s:%d", 
               sock, inet_ntoa((struct in_addr){sock->bind_addr.ip}), sock->bind_addr.port);
    int hashval = cal_hash(sock->bind_addr.ip, sock->bind_addr.port, 0, 0);
    listen_socks[hashval] = sock;
    DEBUG_DETAIL("Socket已注册到listen_socks哈希表，哈希值为 %d", hashval);

    // 初始化半连接队列和全连接队列（循环队列）
    // 初始化队列数组元素
    int index;
    for(index=0; index<MAX_SOCK; index++) {
        syn_queue.queue[index] = NULL;
        established_queue.queue[index] = NULL;
    }
    
    // 初始化循环队列的控制参数
    syn_queue.front = 0;
    syn_queue.rear = 0;
    syn_queue.count = 0;
    established_queue.front = 0;
    established_queue.rear = 0;
    established_queue.count = 0;
    
    // 初始化队列锁和条件变量
    pthread_mutex_init(&syn_queue_lock, NULL);
    pthread_mutex_init(&established_queue_lock, NULL);
    pthread_cond_init(&syn_queue_not_empty, NULL);
    pthread_cond_init(&established_queue_not_empty, NULL);

    // 初始化计时器
    signal(SIGALRM, timeout_handler);
    
    return 0;
}

/*
如果全连接队列有条目，取出并返回该条目
否则阻塞等待
*/
tju_tcp_t* tju_accept(tju_tcp_t* listen_sock){
    tju_tcp_t* new_conn = NULL;
    DEBUG_DETAIL("在监听socket %p 上调用accept()", listen_sock);
    
    // 检查socket是否处于LISTEN状态
    if(listen_sock->state != LISTEN) {
        DEBUG_STATE("accept: socket %p 不在LISTEN状态", listen_sock);
        return NULL;
    }
    
    // 加锁保护全连接队列的访问
    pthread_mutex_lock(&established_queue_lock);
    
    // 阻塞等待，直到全连接队列不为空（等待三次握手第三阶段完成）
    while (established_queue_is_empty()) {
        DEBUG_STATE("阻塞在accept()，等待三次握手第三阶段完成...");
        // 释放锁并等待条件变量信号
        pthread_cond_wait(&established_queue_not_empty, &established_queue_lock);
    }
    DEBUG_STATE("三次握手第三阶段已完成，已建立队列中有可用连接");
    
    // 队列不为空，从队列头部取出socket
    new_conn = established_queue_dequeue();
    DEBUG_STATE("已接受新连接: socket %p, 客户端 %s:%d", 
               new_conn, 
               inet_ntoa((struct in_addr){new_conn->established_remote_addr.ip}), 
               new_conn->established_remote_addr.port);
    DEBUG_DETAIL("新连接详情 - 本地地址: %s:%d, 远程地址: %s:%d", 
                inet_ntoa((struct in_addr){new_conn->established_local_addr.ip}), 
                new_conn->established_local_addr.port,
                inet_ntoa((struct in_addr){new_conn->established_remote_addr.ip}), 
                new_conn->established_remote_addr.port);
    
    pthread_mutex_unlock(&established_queue_lock);

    curr_sock = new_conn;
    DEBUG_DETAIL("curr_sock已更新为新连接socket %p，准备返回", new_conn);
    
    return new_conn;
}


/*
设置本地和远端地址

*/
int tju_connect(tju_tcp_t* sock, tju_sock_addr target_addr){
    DEBUG_STATE("开始连接过程，socket=%p，目标地址=%s:%d", sock, inet_ntoa((struct in_addr){target_addr.ip}), target_addr.port);
    
    // 检查sock是否处于CLOSED状态
    if(sock->state != CLOSED) {
        DEBUG_STATE("connect: socket %p 不在CLOSED状态", sock);
        return -1;
    }
    
    curr_sock = sock;
    sock->established_remote_addr = target_addr;
    DEBUG_DETAIL("设置远程地址: %s:%d", inet_ntoa((struct in_addr){target_addr.ip}), target_addr.port);

    tju_sock_addr local_addr;
    local_addr.ip = inet_network(CLIENT_IP);
    local_addr.port = 5678; // 连接方进行connect连接的时候 内核中是随机分配一个可用的端口
    sock->established_local_addr = local_addr;
    DEBUG_DETAIL("设置本地地址: %s:%d", inet_ntoa((struct in_addr){local_addr.ip}), local_addr.port);

    // 将建立了连接的socket放入内核 已建立连接哈希表中
    // 否则无法收到来自服务器的ACK包
    int hashval = cal_hash(local_addr.ip, local_addr.port, target_addr.ip, target_addr.port);
    established_socks[hashval] = sock;
    DEBUG_DETAIL("Socket已预注册到established_socks哈希表，哈希值为 %d", hashval);

    // 初始化计时器
    signal(SIGALRM, timeout_handler);
    DEBUG_DETAIL("定时器信号处理函数已注册");

    // 初始化窗口信息
    DEBUG_DETAIL("初始化窗口信息 - 发送窗口nextseq=%u, base=%u，接收窗口expect_seq=%u", 
                 sock->window.wnd_send->nextseq, sock->window.wnd_send->base, sock->window.wnd_recv->expect_seq);

    //发送SYN包（三次握手的第一个包）
    pthread_mutex_lock(&(sock->send_lock));
    DEBUG_PACKET("客户端发送SYN包到 %s:%d，开始三次握手第一阶段", 
                 inet_ntoa((struct in_addr){target_addr.ip}), target_addr.port);
    // 分配内存，创建包
    struct timeval now;
    gettimeofday(&now, NULL);
    tju_packet_t* packet = create_packet(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
              DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, SYN_FLAG_MASK, 1, 0, NULL, 0, now);
    DEBUG_DETAIL("创建SYN包 - seq=%u, flags=0x%x, 长度=%u", 
                packet->header.seq_num, packet->header.flags, DEFAULT_HEADER_LEN);
    
    // 使用packet_to_buf转化为字符串并发送
    char* msg = packet_to_buf(packet);
    sendToLayer3(msg, DEFAULT_HEADER_LEN);

    free(msg);
    DEBUG_PACKET("SYN包已发送到网络层");
    
    // 将包加入nacked链表
    add_nacked_packet(sock, packet);
    DEBUG_DETAIL("SYN包已加入未确认链表，等待ACK");
    
    // 改变状态为SYN_SENT
    sock->state = SYN_SENT;
    DEBUG_STATE("Socket %p 进入SYN_SENT状态，等待SYN-ACK响应", sock);

    //更新发送窗口
    sock->window.wnd_send->nextseq += 1;
    DEBUG_DETAIL("发送窗口已更新: nextseq = %u", sock->window.wnd_send->nextseq);
    
    // 启动定时器，设置超时重传
    start_timer(sock);
    DEBUG_DETAIL("已启动定时器，超时重传时间: %ld.%06ld秒", 
                (long)sock->window.wnd_send->timeout.it_value.tv_sec, 
                (long)sock->window.wnd_send->timeout.it_value.tv_usec);
    

    pthread_mutex_unlock(&(sock->send_lock));
    
    // 等待连接建立
    DEBUG_STATE("等待三次握手完成，连接建立中...");
    pthread_mutex_lock(&(sock->state_lock));
    while(sock->state != ESTABLISHED){
        DEBUG_DETAIL("等待状态变为ESTABLISHED，当前状态: %d", sock->state);
        pthread_cond_wait(&sock->state_change, &(sock->state_lock));
    }
    DEBUG_STATE("三次握手完成，连接已建立，socket=%p", sock);
    pthread_mutex_unlock(&(sock->state_lock));

    return 0;
}

int tju_send(tju_tcp_t* sock, const void *buffer, int len){
    DEBUG_STATE("开始发送数据，sock=%p，请求长度=%d", sock, len);
    
    // 检查是否可以发送数据
    if(sock->state != ESTABLISHED) {
        DEBUG_STATE("send: socket %p 不在ESTABLISHED状态，当前状态: %d", sock, sock->state);
        pthread_mutex_unlock(&(sock->send_lock));
        return -1;
    }
    
    DEBUG_PACKET("准备发送数据包，长度=%d，发送窗口状态: nextseq=%u, base=%u", 
                 len, sock->window.wnd_send->nextseq, sock->window.wnd_send->base);
    
    int total_sent = 0;
    int current_offset = 0;
    int packet_count = 0;
    
    // 将数据分成多个包发送，每个包的数据量不超过MAX_DLEN
    while (total_sent < len) {
        pthread_mutex_lock(&(sock->send_lock));
        // 检查接收方窗口是否已满
        while(sock->window.wnd_send->rwnd == 0) {
            DEBUG_DETAIL("接收方窗口已满，无法发送更多数据");
            // 设置状态为STOP_WAIT
            sock->state = STOP_WAIT;
            DEBUG_STATE("Socket %p 进入STOP_WAIT状态，等待新rwnd", sock);
            
            // 停止并重置计时器
            stop_timer(sock);
            reset_timer(sock);
            
            // 发送零窗口探测包
            struct timeval now;
            gettimeofday(&now, NULL);
            char* zero_window_msg = create_packet_buf(
                sock->established_local_addr.port,
                sock->established_remote_addr.port,
                sock->window.wnd_send->nextseq,
                sock->window.wnd_recv->expect_seq,
                DEFAULT_HEADER_LEN,
                DEFAULT_HEADER_LEN,
                ZERO_WINDOW_PROBE_MASK,
                1,
                0,
                NULL,
                0,
                now
            );
            sendToLayer3(zero_window_msg, DEFAULT_HEADER_LEN);
            free(zero_window_msg);
            
            DEBUG_PACKET("发送零窗口探测包，seq=%u, ack=%u", 
                        sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq);
            
            // 启动计时器
            start_timer(sock);
            
            // 等待新的rwnd
            pthread_cond_wait(&sock->window.wnd_send->recv_window_not_full, &(sock->send_lock));
            pthread_mutex_unlock(&(sock->send_lock));
        }

        // 计算当前包的数据长度，为MAX_DLEN，剩余数据量和剩余发送窗口大小的较小值
        int current_packet_len = len - total_sent;
        if (current_packet_len > MAX_DLEN) current_packet_len = MAX_DLEN;
        int nacked_size = sock->window.wnd_send->nextseq - sock->window.wnd_send->base; //用于防止计算剩余发送窗口大小结果为负数时的溢出
        if (current_packet_len + nacked_size > sock->window.wnd_send->window_size) 
            current_packet_len = sock->window.wnd_send->window_size - nacked_size;
        
        // 如果发送窗口已满，阻塞等待
        while(current_packet_len <= 0){
            DEBUG_DETAIL("发送窗口已满，阻塞等待");
            pthread_cond_wait(&sock->window.wnd_send->send_window_not_full, &(sock->send_lock));
            if(sock->window.wnd_send->rwnd == 0) break;
            current_packet_len = len - total_sent;
            if (current_packet_len > MAX_DLEN) current_packet_len = MAX_DLEN;
            nacked_size = sock->window.wnd_send->nextseq - sock->window.wnd_send->base;
            if (current_packet_len + nacked_size > sock->window.wnd_send->window_size){
                current_packet_len = sock->window.wnd_send->window_size - nacked_size;
            }
        }
        if(sock->window.wnd_send->rwnd == 0){// 接收方窗口已满，无法发送更多数据，进入下一个循环发送零窗口探测报文
            pthread_mutex_unlock(&(sock->send_lock));
            continue;
        }
        DEBUG_DETAIL("发送第%d个数据包，长度=%d，偏移量=%d", 
                    packet_count + 1, current_packet_len, current_offset);
                    
        // 确认当前包的序列号+长度是否在发送窗口内
        if(sock->window.wnd_send->nextseq + current_packet_len > sock->window.wnd_send->base + sock->window.wnd_send->window_size) {
            DEBUG_DETAIL("当前包的序列号+长度超出发送窗口，nextseq=%u, base=%u, window_size=%u, current_packet_len=%d", 
                        sock->window.wnd_send->nextseq, sock->window.wnd_send->base, sock->window.wnd_send->window_size, current_packet_len);
            exit(0);
        }

        // 为当前包分配内存
        char* data = malloc(current_packet_len);
        memcpy(data, (char*)buffer + current_offset, current_packet_len);

        // 创建并发送数据包
        char* msg;
        struct timeval now;
        gettimeofday(&now, NULL);
        tju_packet_t* packet = create_packet(
            sock->established_local_addr.port, 
            sock->established_remote_addr.port, 
            sock->window.wnd_send->nextseq, 
            sock->window.wnd_recv->expect_seq, 
            DEFAULT_HEADER_LEN, 
            DEFAULT_HEADER_LEN + current_packet_len, 
            NO_FLAG, 
            1, 
            0, 
            data, 
            current_packet_len,
            now
        );
        
        msg = packet_to_buf(packet);
        sendToLayer3(msg, DEFAULT_HEADER_LEN + current_packet_len);
        free(msg);
        
        // 如果是第一个发送的包，启动定时器
        if(sock->window.wnd_send->base == sock->window.wnd_send->nextseq) {
            reset_timer(sock);
            start_timer(sock);
        }
        
        // 将数据包添加到未确认链表
        add_nacked_packet(sock, packet);
        DEBUG_PACKET("数据包已发送，seq=%u，长度=%d，等待确认", 
                    sock->window.wnd_send->nextseq, current_packet_len);
        
        // 更新nextseq和统计信息
        sock->window.wnd_send->nextseq += current_packet_len;
        total_sent += current_packet_len;
        current_offset += current_packet_len;
        packet_count++;
        
        DEBUG_DETAIL("更新发送窗口: nextseq = %u，已发送总数=%d/%d", 
                    sock->window.wnd_send->nextseq, total_sent, len);
        pthread_mutex_unlock(&(sock->send_lock));
    }

    DEBUG_STATE("tju_send()完成，成功发送%d字节数据，共%d个包", len, packet_count);
    return len;
}
int tju_recv(tju_tcp_t* sock, void *buffer, int len){
    DEBUG_STATE("开始接收数据，sock=%p，请求读取长度=%d", sock, len);
    
    pthread_mutex_lock(&(sock->recv_lock)); // 加锁
    while(sock->received_len <= 0) {
        DEBUG_STATE("接收缓冲区为空，在sock=%p上阻塞等待数据", sock);
        pthread_cond_wait(&sock->wait_cond, &(sock->recv_lock)); // 等待信号
        DEBUG_STATE("收到数据信号，sock=%p的接收缓冲区有数据", sock);
    }
    
    int read_len = 0;
    if (sock->received_len >= len) { // 从中读取len长度的数据
        read_len = len;
        DEBUG_DETAIL("接收缓冲区数据充足，读取请求的全部长度=%d", read_len);
    } else {
        read_len = sock->received_len; // 读取sock->received_len长度的数据(全读出来)
        DEBUG_DETAIL("接收缓冲区数据不足，读取全部现有数据，长度=%d/请求=%d", read_len, len);
    }

    memcpy(buffer, sock->received_buf, read_len);
    
    if(read_len < sock->received_len) { // 还剩下一些
        char* new_buf = malloc(sock->received_len - read_len);
        memcpy(new_buf, sock->received_buf + read_len, sock->received_len - read_len);
        free(sock->received_buf);
        sock->received_len -= read_len;
        sock->received_buf = new_buf;
        // 更新接收窗口
        sock->window.wnd_recv->window_size = TCP_RECVWN_SIZE - sock->received_len;
        TRACE_RWND(sock->window.wnd_recv->window_size);
        DEBUG_DETAIL("接收缓冲区剩余数据长度=%d，已重新分配内存", sock->received_len);
    } else {
        free(sock->received_buf);
        sock->received_buf = NULL;
        sock->received_len = 0;
        // 更新接收窗口
        sock->window.wnd_recv->window_size = TCP_RECVWN_SIZE;
        TRACE_RWND(sock->window.wnd_recv->window_size);
        DEBUG_DETAIL("接收缓冲区已清空");
    }
    pthread_mutex_unlock(&(sock->recv_lock)); // 解锁
    
    DEBUG_STATE("tju_recv()完成，成功读取%d字节数据", read_len);
    return read_len;
}

int tju_handle_packet(tju_tcp_t* sock, char* pkt){
    uint16_t remote_port = get_src(pkt);
    uint16_t local_port = get_dst(pkt);
    uint32_t ack = get_ack(pkt);
    uint32_t seq = get_seq(pkt);
    uint16_t hlen = get_hlen(pkt);
    uint16_t plen = get_plen(pkt);
    uint8_t flags = get_flags(pkt);
    uint16_t adv_window = get_advertised_window(pkt);
    struct timeval sent_time;
    get_sent_time(pkt, &sent_time);
    
    switch (sock->state)
    {
    case CLOSED:
        break;
    case LISTEN:
        /*
        收到SYN包
        创建一个新的socket
        改变状态为SYN_RECV
        加入established_socks哈希表，以进行后续的数据传输
        发送SYN-ACK包
        加入半连接队列
        */
        if(flags & SYN_FLAG_MASK){   
            DEBUG_PACKET("服务器收到三次握手的第一个包(SYN)，来自 %s:%d, seq=%u", 
                        inet_ntoa((struct in_addr){inet_network(CLIENT_IP)}), remote_port, seq);
            // 创建一个新的socket
            tju_tcp_t* new_sock = tju_socket();
            curr_sock = new_sock;
            DEBUG_STATE("创建新socket %p 处理连接请求", new_sock);

            // 改变状态为SYN_RECV
            new_sock->state = SYN_RECV;
            DEBUG_STATE("新socket %p 进入SYN_RECV状态", new_sock);

            //更新接收窗口
            pthread_mutex_lock(&(new_sock->recv_lock));
            new_sock->window.wnd_recv->expect_seq = seq + 1;
            DEBUG_DETAIL("初始化接收窗口: expect_seq = %u", new_sock->window.wnd_recv->expect_seq);
            pthread_mutex_unlock(&(new_sock->recv_lock));

            //初始化新socket，并将其加入已建立连接哈希表
            DEBUG_DETAIL("[三次握手] 初始化new_socket地址信息 - 客户端IP=%s, 端口=%d", 
                   CLIENT_IP, remote_port);
            new_sock->established_remote_addr.ip = inet_network(CLIENT_IP);
            new_sock->established_remote_addr.port = remote_port;
            new_sock->established_local_addr.ip = inet_network(SERVER_IP);
            new_sock->established_local_addr.port = local_port;

            int hashval = cal_hash(new_sock->established_local_addr.ip, new_sock->established_local_addr.port,
                                  new_sock->established_remote_addr.ip, new_sock->established_remote_addr.port);
            established_socks[hashval] = new_sock;
            DEBUG_STATE("新socket %p 已加入已建立连接哈希表，哈希值=%d", new_sock, hashval);
            
            // 发送SYN-ACK包（三次握手的第二个包）
            pthread_mutex_lock(&(new_sock->send_lock));
            DEBUG_PACKET("准备发送SYN-ACK包，三次握手的第二个包");
            // 分配内存，创建包
            struct timeval now;
            gettimeofday(&now, NULL);
            tju_packet_t* packet = create_packet(local_port, remote_port, new_sock->window.wnd_send->nextseq, new_sock->window.wnd_recv->expect_seq, 
                      DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, SYN_FLAG_MASK | ACK_FLAG_MASK, 1, 0, NULL, 0, now);
            
            // 使用packet_to_buf转化为字符串并发送
            char* msg = packet_to_buf(packet);
            sendToLayer3(msg, DEFAULT_HEADER_LEN);
            free(msg);
            
            // 将包加入nacked链表
            add_nacked_packet(new_sock, packet);
            DEBUG_DETAIL("SYN-ACK包已加入未确认链表，seq=%u", packet->header.seq_num);
            
            // 更新发送窗口
            new_sock->window.wnd_send->nextseq += 1;
            DEBUG_DETAIL("更新发送窗口: nextseq = %u", new_sock->window.wnd_send->nextseq);
            
            // 启动定时器
            start_timer(new_sock);
            DEBUG_DETAIL("为socket %p 启动定时器，用于SYN-ACK包重传", new_sock);
            
            pthread_mutex_unlock(&(new_sock->send_lock));

            // 加入半连接队列
            pthread_mutex_lock(&syn_queue_lock);
            DEBUG_DETAIL("成功申请锁，准备添加到SYN队列");
            syn_queue_enqueue(new_sock);
            DEBUG_STATE("Socket %p 已添加到SYN队列（半连接队列）", new_sock);
            pthread_mutex_unlock(&syn_queue_lock);
            pthread_cond_signal(&syn_queue_not_empty);
            DEBUG_DETAIL("已通知可能等待的线程处理新的连接请求");
        }
        break;
    case SYN_SENT:
        /*
        收到SYN-ACK包
        改变状态为ESTABLISHED
        发送ACK包
        唤醒阻塞在connect函数中的线程
        */
        if((flags & SYN_FLAG_MASK) && (flags & ACK_FLAG_MASK)){
            // 收到SYN-ACK包
            DEBUG_PACKET("客户端收到SYN-ACK包，来自 %s:%d, seq=%u, ack=%u", 
                        inet_ntoa((struct in_addr){sock->established_remote_addr.ip}), sock->established_remote_addr.port, seq, ack);
            
            // 改变状态为ESTABLISHED
            sock->state = ESTABLISHED;
            DEBUG_STATE("Socket %p 进入ESTABLISHED状态", sock);
            
            // 停止定时器
            stop_timer(sock);
            
            // 移除未确认包并更新窗口
            pthread_mutex_lock(&(sock->send_lock));
            remove_nacked_packet(sock, ack);
            sock->window.wnd_send->base += 1; // 更新发送窗口的base
            pthread_mutex_unlock(&(sock->send_lock));

            // 更新接收窗口
            pthread_mutex_lock(&(sock->recv_lock));
            sock->window.wnd_recv->expect_seq = seq + 1;
            pthread_mutex_unlock(&(sock->recv_lock));

            // 发送第三次握手ACK包
            pthread_mutex_lock(&(sock->send_lock));
            struct timeval now;
            gettimeofday(&now, NULL);
            tju_packet_t* packet = create_packet(sock->established_local_addr.port, sock->established_remote_addr.port, 
                      sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
                      DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, ACK_FLAG_MASK, 1, 0, NULL, 0, now);
            
            char* msg;
            msg = packet_to_buf(packet);
            sendToLayer3(msg, DEFAULT_HEADER_LEN);
            free(msg);
            free(packet);

            // 更新发送窗口 - 这种ACK不需要被确认，所以同步更新base和nextseq
            sock->window.wnd_send->nextseq += 1;
            sock->window.wnd_send->base = sock->window.wnd_send->nextseq; // 同步更新base
            pthread_mutex_unlock(&(sock->send_lock));

            // 唤醒阻塞在connect函数中的线程
            pthread_mutex_lock(&sock->state_lock);
            pthread_cond_signal(&sock->state_change);
            DEBUG_STATE("唤醒阻塞在connect()上的线程");
            pthread_mutex_unlock(&sock->state_lock);
        }
        break;
    case SYN_RECV:
        /*
        收到ACK包
        从半连接队列中取出socket
        改变状态为ESTABLISHED
        加入全连接队列
        唤醒阻塞在accept函数中的线程
        */
        if((flags & ACK_FLAG_MASK)){
            // 收到ACK包
            DEBUG_PACKET("服务器收到ACK包，来自 %s:%d, seq=%u, ack=%u", 
                        inet_ntoa((struct in_addr){inet_network(CLIENT_IP)}), remote_port, seq, ack);
            
            // 从半连接队列中取出socket
            tju_tcp_t* new_sock = NULL;
            pthread_mutex_lock(&syn_queue_lock);
            while((new_sock = syn_queue_dequeue()) == NULL) {
                pthread_cond_wait(&syn_queue_not_empty, &syn_queue_lock);
            }
            
            if(seq != new_sock->window.wnd_recv->expect_seq){
                DEBUG_STATE("ACK seq错误, expect_seq: %u, seq: %u", new_sock->window.wnd_recv->expect_seq, seq);
                //放回半连接队列
                syn_queue_enqueue(new_sock);
                pthread_mutex_unlock(&syn_queue_lock);
                return -1;
            }
            
            pthread_mutex_unlock(&syn_queue_lock);
            
            // 停止定时器
            stop_timer(new_sock);
            
            // 移除未确认包并更新窗口
            pthread_mutex_lock(&(new_sock->send_lock));
            remove_nacked_packet(new_sock, ack);
            new_sock->window.wnd_send->base += 1; // 更新发送窗口的base
            pthread_mutex_unlock(&(new_sock->send_lock));
            
            // 更新接收窗口
            pthread_mutex_lock(&(new_sock->recv_lock));
            new_sock->window.wnd_recv->expect_seq = seq + 1;
            pthread_mutex_unlock(&(new_sock->recv_lock));
            
            // 改变状态为ESTABLISHED
            new_sock->state = ESTABLISHED;
            DEBUG_STATE("[关键] Socket %p 进入ESTABLISHED状态", new_sock);

            // 加入全连接队列
            pthread_mutex_lock(&established_queue_lock);
            established_queue_enqueue(new_sock);
            DEBUG_STATE("Socket %p 已添加到已建立队列", new_sock);
            pthread_mutex_unlock(&established_queue_lock);
            // 唤醒阻塞在accept函数中的线程
            pthread_mutex_lock(&established_queue_lock);
            pthread_cond_signal(&established_queue_not_empty);
            DEBUG_STATE("唤醒阻塞在accept()上的线程");
            pthread_mutex_unlock(&established_queue_lock);
        }
        break;
    case ESTABLISHED: {
        /*
        处理收到的普通数据包
        */
        uint32_t data_len = plen - hlen;
        if(data_len > 0) {
            DEBUG_PACKET("收到普通数据包，长度=%u，seq=%u，ack=%u，sock=%p", data_len, seq, ack, sock);
            // 接收数据
            pthread_mutex_lock(&(sock->recv_lock));
            // 检查序列号是否正确
            if(seq != sock->window.wnd_recv->expect_seq){
                // 序列号错误，判断是否在接收窗口内
                // 如果在窗口范围外，直接丢弃，否则缓存该包
                if(seq < sock->window.wnd_recv->expect_seq || seq > sock->window.wnd_recv->expect_seq + sock->window.wnd_recv->window_size){
                    DEBUG_STATE("seq错误, 在接收窗口外, 窗口范围: [%u, %u], seq: %u", sock->window.wnd_recv->expect_seq, sock->window.wnd_recv->expect_seq + sock->window.wnd_recv->window_size, seq);
                    // 直接丢弃该包
                    // 发送ACK包
                    pthread_mutex_lock(&(sock->send_lock));
                    send_ack(sock, sent_time);
                    pthread_mutex_unlock(&(sock->send_lock));
                    pthread_mutex_unlock(&(sock->recv_lock));
                    return 0;
                }else{
                    // 缓存乱序包
                    DEBUG_DETAIL("收到乱序包，seq=%u，expect_seq=%u，缓存该包", seq, sock->window.wnd_recv->expect_seq);
                    add_received_packet(sock, seq, data_len, pkt + DEFAULT_HEADER_LEN);
                    // 发送累积ACK包
                    pthread_mutex_lock(&(sock->send_lock));
                    send_ack(sock, sent_time);
                    pthread_mutex_unlock(&(sock->send_lock));
                    pthread_mutex_unlock(&(sock->recv_lock));
                    return 0;
                }
            }
            
            // 将数据放入接收缓冲区
            if(sock->received_buf == NULL){
                sock->received_buf = malloc(data_len);
            }else {
                sock->received_buf = realloc(sock->received_buf, sock->received_len + data_len);
            }
            memcpy(sock->received_buf + sock->received_len, pkt + DEFAULT_HEADER_LEN, data_len);
            // 更新接收缓冲区长度
            sock->received_len += data_len;
            // 更新期望的序列号
            sock->window.wnd_recv->expect_seq = seq + data_len;
            TRACE_DELV(seq, data_len);
            
            // 检查在received_packet链表中是否有与当前包连续的包
            // 如果有连续的包，从链表中取出，将数据追加到接收缓冲区，直到没有连续的包
            received_packet_t* current = sock->window.wnd_recv->head;
            while(current != NULL && current->seq == sock->window.wnd_recv->expect_seq){
                // 将数据追加到接收缓冲区
                sock->received_buf = realloc(sock->received_buf, sock->received_len + current->len);
                memcpy(sock->received_buf + sock->received_len, current->data, current->len);
                TRACE_DELV(current->seq, current->len);
                // 更新接收缓冲区长度
                sock->received_len += current->len;
                data_len += current->len;
                // 更新期望的序列号
                sock->window.wnd_recv->expect_seq = current->seq + current->len;
                // 移除已处理的包
                remove_received_packet(sock, current->seq);
                current = sock->window.wnd_recv->head;
            }
            
            DEBUG_DETAIL("接收缓冲区当前长度: %u，新增数据长度: %u", sock->received_len, data_len);

            // 更新接收窗口
            sock->window.wnd_recv->window_size = TCP_RECVWN_SIZE - sock->received_len;
            if(sock->window.wnd_recv->window_size <= 0){
                DEBUG_STATE("接收窗口已占满");
                sock->window.wnd_recv->window_size = 0;
            }
            TRACE_RWND(sock->window.wnd_recv->window_size);
            
            // 唤醒等待数据的线程
            pthread_cond_signal(&sock->wait_cond);
            pthread_mutex_unlock(&(sock->recv_lock));
            
            // 发送累积ACK包
            pthread_mutex_lock(&(sock->send_lock));
            send_ack(sock, sent_time);
            pthread_mutex_unlock(&(sock->send_lock));
        }
        
        /*
        收到FIN包
        发送ACK包
        改变状态为CLOSE_WAIT
        检查received_packet链表是否为空，确定是否有ack未发送
        如果没有数据，发送FIN-ACK包
        改变状态为LAST_ACK
        */
        if((flags & FIN_FLAG_MASK) && !(flags & SYN_FLAG_MASK) && !(flags & ACK_FLAG_MASK)){
            if(seq != sock->window.wnd_recv->expect_seq){
                DEBUG_STATE("FIN seq错误, expect_seq: %u, seq: %u", sock->window.wnd_recv->expect_seq, seq);
                return -1;
            }
            
            DEBUG_STATE("接收到FIN包，sock=%p，开始四次挥手过程", sock);
            
            // 更新接收窗口
            pthread_mutex_lock(&(sock->recv_lock));
            sock->window.wnd_recv->expect_seq = seq + 1;
            pthread_mutex_unlock(&(sock->recv_lock));
            
            // 发送ACK包（四次挥手的第二个包）
            pthread_mutex_lock(&(sock->send_lock));
            char* msg;
            struct timeval now;
            gettimeofday(&now, NULL);
            msg = create_packet_buf(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
                      DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, ACK_FLAG_MASK, 1, 0, NULL, 0, now);
            sendToLayer3(msg, DEFAULT_HEADER_LEN);
            free(msg);
            
            // 更新发送窗口 - 这种ACK不需要被确认，所以同步更新base和nextseq
            sock->window.wnd_send->nextseq += 1;
            sock->window.wnd_send->base = sock->window.wnd_send->nextseq; // 同步更新base
            pthread_mutex_unlock(&(sock->send_lock));
            
            // 改变状态为CLOSE_WAIT
            sock->state = CLOSE_WAIT;
            DEBUG_STATE("Socket %p 进入CLOSE_WAIT状态", sock);
            
            // 检查received_packet链表是否为空，不为空则忙等待
            while(sock->window.wnd_recv->head != NULL){}
            
            if(sock->window.wnd_recv->head == NULL){
                // 发送FIN-ACK包（四次挥手的第三个包）
                pthread_mutex_lock(&(sock->send_lock));
                DEBUG_STATE("接收缓冲区为空，发送FIN-ACK包关闭连接");
                
                // 分配内存，创建包
                struct timeval now;
                gettimeofday(&now, NULL);
                tju_packet_t* packet = create_packet(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
                          DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, FIN_FLAG_MASK | ACK_FLAG_MASK, 1, 0, NULL, 0, now);
                
                // 使用packet_to_buf转化为字符串并发送
                char* msg = packet_to_buf(packet);
                sendToLayer3(msg, DEFAULT_HEADER_LEN);
                free(msg);
                
                // 将包加入nacked链表
                add_nacked_packet(sock, packet);
                
                // 更新发送窗口
                sock->window.wnd_send->nextseq += 1;
                
                // 启动定时器
                start_timer(sock);
                
                pthread_mutex_unlock(&(sock->send_lock));
                
                // 改变状态为LAST_ACK
                sock->state = LAST_ACK;
                DEBUG_STATE("Socket %p 进入LAST_ACK状态，等待最终ACK", sock);
            }
        }
        
        /*
        如果收到SYN-ACK包，说明之前发送的ACK丢失，需要重新发送ACK
        */
        if((flags & SYN_FLAG_MASK) && (flags & ACK_FLAG_MASK)){
            DEBUG_PACKET("在ESTABLISHED状态收到SYN-ACK包，说明之前的ACK丢失，需要重发ACK，sock=%p, seq=%u, ack=%u", sock, seq, ack);
            // 发送ACK包
            pthread_mutex_lock(&(sock->send_lock));
            DEBUG_PACKET("重发ACK包（ESTABLISHED状态）");
            char* msg;
            struct timeval now;
            gettimeofday(&now, NULL);
            msg = create_packet_buf(sock->established_local_addr.port, sock->established_remote_addr.port, 1, 1, 
                      DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, ACK_FLAG_MASK, 1, 0, NULL, 0, now);
            sendToLayer3(msg, DEFAULT_HEADER_LEN);
            free(msg);
            DEBUG_DETAIL("更新发送窗口: nextseq = %u, base = %u", sock->window.wnd_send->nextseq, sock->window.wnd_send->base);
            pthread_mutex_unlock(&(sock->send_lock));
        }
        
        /*
        收到普通ACK包
        更新发送窗口
        */
        if((flags & ACK_FLAG_MASK) && !(flags & SYN_FLAG_MASK) && !(flags & FIN_FLAG_MASK) && !(flags & ZERO_WINDOW_PROBE_MASK) && data_len == 0){
            DEBUG_PACKET("收到ACK包，sock=%p, ack=%u, adv_window=%u", sock, ack, adv_window);
            if(ack > sock->window.wnd_send->base){ //一般情况，ack大于base
                pthread_mutex_lock(&(sock->send_lock));
                sock->window.wnd_send->base = ack;
                sock->window.wnd_send->rwnd = adv_window; //更新rwnd
                TRACE_RWND(sock->window.wnd_send->rwnd);
                // 更新cwnd
                if(sock->window.wnd_send->congestion_status == SLOW_START){
                    sock->window.wnd_send->cwnd *= 2;
                    if(sock->window.wnd_send->cwnd >= sock->window.wnd_send->ssthresh){
                        sock->window.wnd_send->cwnd = sock->window.wnd_send->ssthresh;
                        sock->window.wnd_send->congestion_status = CONGESTION_AVOIDANCE;
                    }
                    TRACE_CWND(sock->window.wnd_send->congestion_status, sock->window.wnd_send->cwnd);
                }else if(sock->window.wnd_send->congestion_status == CONGESTION_AVOIDANCE){
                    sock->window.wnd_send->cwnd += MAX_DLEN;
                    if(sock->window.wnd_send->cwnd > TCP_RECVWN_SIZE) sock->window.wnd_send->cwnd = TCP_RECVWN_SIZE;
                    TRACE_CWND(sock->window.wnd_send->congestion_status, sock->window.wnd_send->cwnd);
                }
                // 更新窗口大小
                sock->window.wnd_send->window_size = sock->window.wnd_send->rwnd < sock->window.wnd_send->cwnd ? sock->window.wnd_send->rwnd : sock->window.wnd_send->cwnd; //更新窗口大小
                TRACE_SWND(sock->window.wnd_send->window_size);

                struct timeval now;
                gettimeofday(&now, NULL);
                
                // 通知发送线程发送窗口可能有空间
                pthread_cond_signal(&(sock->window.wnd_send->send_window_not_full));
                
                sock->window.wnd_send->ack_cnt = 0;
                DEBUG_DETAIL("更新发送窗口: base = %u, rwnd = %u, window_size = %u", sock->window.wnd_send->base, sock->window.wnd_send->rwnd, sock->window.wnd_send->window_size);
                // 停止计时器
                stop_timer(sock);
                
                // 移除已确认的数据包
                remove_nacked_packet(sock, ack);

                // 更新RTT
                if(sent_time.tv_sec >= 0 || sent_time.tv_usec >= 0){
                    // DEBUG_DETAIL("准备更新RTT");
                    // 使用send_time和now计算RTT，注意使用浮点运算
                    float rtt = (now.tv_sec - sent_time.tv_sec) * 1000.0 + (now.tv_usec - sent_time.tv_usec) / 1000.0;
                    DEBUG_DETAIL("收到sent_time=%ld.%06ld s, now=%ld.%06ld s, RTT样本: %f ms", sent_time.tv_sec, sent_time.tv_usec, now.tv_sec, now.tv_usec, (double)rtt);
                    
                    // 判断是否是首次计算RTT
                    if(sock->window.wnd_send->estimated_rtt == 0) {
                        // 首次计算RTT
                        sock->window.wnd_send->estimated_rtt = rtt;
                        sock->window.wnd_send->dev_rtt = rtt / 2.0;
                    } else {
                        // 后续计算RTT
                        sock->window.wnd_send->estimated_rtt = (1 - ALPHA) * sock->window.wnd_send->estimated_rtt + ALPHA * rtt;
                        sock->window.wnd_send->dev_rtt = (1 - BETA) * sock->window.wnd_send->dev_rtt + BETA * fabs(rtt - sock->window.wnd_send->estimated_rtt);
                    }
                    
                    // 计算RTO = μ*SRTT + σ*DevRTT
                    float rto = MU * sock->window.wnd_send->estimated_rtt + SIGMA * sock->window.wnd_send->dev_rtt;
                    
                    // 记录RTT相关事件
                    DEBUG_DETAIL("RTT样本: %f, 估计RTT: %f, 偏差RTT: %f, RTO: %f", (double)rtt, (double)sock->window.wnd_send->estimated_rtt, (double)sock->window.wnd_send->dev_rtt, rto);
                    
                    // 更新timeout，转换为秒和微秒
                    if(rto > RTO){
                        sock->window.wnd_send->timeout.it_value.tv_sec = (uint32_t)(rto / 1000.0);
                        sock->window.wnd_send->timeout.it_value.tv_usec = (uint32_t)((rto - (sock->window.wnd_send->timeout.it_value.tv_sec * 1000.0)) * 1000.0);
                    }else{ //如果RTO小于默认值，设置为默认值
                        sock->window.wnd_send->timeout.it_value.tv_sec = 0;
                        sock->window.wnd_send->timeout.it_value.tv_usec = RTO * 1000;
                    }
                    TRACE_RTTS(rtt, sock->window.wnd_send->estimated_rtt, sock->window.wnd_send->dev_rtt, sock->window.wnd_send->timeout.it_value.tv_sec * 1000.0 + sock->window.wnd_send->timeout.it_value.tv_usec / 1000.0);
                }
                
                // 如果有未确认的包，大概率也已经丢失，立刻重传未确认链表中最近开始的retransmit_num个包（如有），并更新包的sent_timesent_time
                // 重传后重置timeout，启动定时器
                if(sock->window.wnd_send->head != NULL){
                    int retransmit_num = 1;
                    nacked_packet_t* temp = sock->window.wnd_send->head;
                    for(int i=0;i<retransmit_num && temp!=NULL;i++){
                        // 发送数据包
                        gettimeofday(&(temp->pkt->sent_time), NULL);
                        char *msg = packet_to_buf(temp->pkt);
                        sendToLayer3(msg, temp->pkt->header.plen);
                        free(msg);
                        // 更新sent_time
                        gettimeofday(&(temp->pkt->sent_time), NULL);
                        // 移动到下一个包
                        temp = temp->next;
                    }
                    // 重置定时器
                    reset_timer(sock);
                    start_timer(sock);
                }
                
                pthread_mutex_unlock(&(sock->send_lock));
            }else if(ack == sock->window.wnd_send->base){ //特殊情况，ack等于base
                // if(sock->window.wnd_send->base == sock->window.wnd_send->nextseq){ // 特殊情况，base等于nextseq
                //     pthread_cond_signal(&(sock->window.wnd_send->send_window_not_full));
                //     return 0;
                // }
                // 增加ack_cnt
                pthread_mutex_lock(&(sock->send_lock));
                sock->window.wnd_send->ack_cnt++;
                DEBUG_DETAIL("更新ack_cnt: %d", sock->window.wnd_send->ack_cnt);
                // 如果ack_cnt超过阈值，触发重传
                if(sock->window.wnd_send->ack_cnt >= 3){ //三次重复ACK，触发重传
                    DEBUG_STATE("检测到三次重复ACK，触发快速重传");
                    pthread_mutex_unlock(&(sock->send_lock));
                    // 重传未确认的包
                    retransmit_nacked_packets(sock);
                    return 0;
                }
                pthread_mutex_unlock(&(sock->send_lock));
            }
        }
        /*
        收到零窗口探测包
        发送ZERO_WINDOW_PROBE-ACK包
        */
        if((flags & ZERO_WINDOW_PROBE_MASK) && !(flags & ACK_FLAG_MASK)){
            DEBUG_STATE("收到零窗口探测包，sock=%p，当前接收窗口: %u", sock, sock->window.wnd_recv->window_size);
            // 发送ZERO_WINDOW_PROBE-ACK包
            pthread_mutex_lock(&(sock->send_lock));
            char* msg;
            struct timeval now;
            gettimeofday(&now, NULL);
            msg = create_packet_buf(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
                      DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, ZERO_WINDOW_PROBE_MASK | ACK_FLAG_MASK, sock->window.wnd_recv->window_size, 0, NULL, 0, now);
            sendToLayer3(msg, DEFAULT_HEADER_LEN);
            free(msg);
            pthread_mutex_unlock(&(sock->send_lock));
        }
        break;
    }
    case FIN_WAIT_1:
        /*
        收到ACK包
        更新窗口
        改变状态为FIN_WAIT_2
        */
        if((flags & ACK_FLAG_MASK) && !(flags & SYN_FLAG_MASK) && !(flags & FIN_FLAG_MASK)){
            DEBUG_STATE("收到FIN的ACK包，sock=%p, ack=%u", sock, ack);
            if(ack != sock->window.wnd_send->nextseq){
                DEBUG_STATE("ACK seq错误, expect_seq: %u, ack: %u", sock->window.wnd_send->nextseq, ack);
                return -1;
            }
            // 停止计时器
            stop_timer(sock);
            // 移除已确认的数据包
            pthread_mutex_lock(&(sock->send_lock));
            remove_nacked_packet(sock, ack);
            // 更新发送窗口 - 使用收到的ack值更新base
            sock->window.wnd_send->base = ack;
            pthread_mutex_unlock(&(sock->send_lock));
            // 更新接收窗口
            pthread_mutex_lock(&(sock->recv_lock));
            sock->window.wnd_recv->expect_seq = seq + 1;
            pthread_mutex_unlock(&(sock->recv_lock));
            // 改变状态为FIN_WAIT_2
            sock->state = FIN_WAIT_2;
            DEBUG_STATE("Socket %p 进入FIN_WAIT_2状态，等待对方关闭", sock);
        }
        /*
        收到FIN包
        同时关闭的情况
        更新接收窗口
        发送ACK包
        进入CLOSING状态
        */
        if((flags & FIN_FLAG_MASK)){
            DEBUG_PACKET("收到FIN包（同时关闭），sock=%p, seq=%u", sock, seq);
            if(seq != sock->window.wnd_recv->expect_seq){
                DEBUG_STATE("FIN seq错误, expect_seq: %u, seq: %u", sock->window.wnd_recv->expect_seq, seq);
                return -1;
            }
            // 更新接收窗口
            pthread_mutex_lock(&(sock->recv_lock));
            sock->window.wnd_recv->expect_seq += 1;
            DEBUG_DETAIL("更新接收窗口: expect_seq = %u", sock->window.wnd_recv->expect_seq);
            pthread_mutex_unlock(&(sock->recv_lock));
            // 发送ACK包
            pthread_mutex_lock(&(sock->send_lock));
            DEBUG_PACKET("发送ACK包确认FIN（同时关闭情况）");
            char* msg;
            struct timeval now;
            gettimeofday(&now, NULL);
            msg = create_packet_buf(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
                      DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, ACK_FLAG_MASK, 1, 0, NULL, 0, now);
            sendToLayer3(msg, DEFAULT_HEADER_LEN);
            free(msg);
            // 更新发送窗口
            sock->window.wnd_send->base += 1;
            sock->window.wnd_send->nextseq += 1;
            DEBUG_DETAIL("更新发送窗口: base = %u, nextseq = %u", sock->window.wnd_send->base, sock->window.wnd_send->nextseq);
            pthread_mutex_unlock(&(sock->send_lock));
            // 改变状态为CLOSING
            sock->state = CLOSING;
            DEBUG_STATE("Socket %p 进入CLOSING状态（同时关闭）", sock);
        }
        break;
    case FIN_WAIT_2:
        /*
        收到FIN-ACK包
        发送ACK包
        改变状态为TIME_WAIT
        启动定时器
        */
        if((flags & FIN_FLAG_MASK) && (flags & ACK_FLAG_MASK)){
            DEBUG_PACKET("收到FIN-ACK包，四次挥手的第三个包，sock=%p, seq=%u, ack=%u", sock, seq, ack);
            // 更新接收窗口
            pthread_mutex_lock(&(sock->recv_lock));
            sock->window.wnd_recv->expect_seq = seq + 1;
            DEBUG_DETAIL("更新接收窗口: expect_seq = %u", sock->window.wnd_recv->expect_seq);
            pthread_mutex_unlock(&(sock->recv_lock));
            // 发送ACK包（四次挥手的第四个包）
            pthread_mutex_lock(&(sock->send_lock));
            DEBUG_PACKET("发送最终ACK包，完成四次挥手");
            char* msg;
            struct timeval now;
            gettimeofday(&now, NULL);
            msg = create_packet_buf(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
                      DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, ACK_FLAG_MASK, 1, 0, NULL, 0, now);
            sendToLayer3(msg, DEFAULT_HEADER_LEN);
            free(msg);
            // 更新发送窗口 - 这种ACK不需要被确认，所以同步更新base和nextseq
            sock->window.wnd_send->nextseq += 1;
            sock->window.wnd_send->base = sock->window.wnd_send->nextseq; // 同步更新base
            DEBUG_DETAIL("更新发送窗口: nextseq = %u, base = %u", sock->window.wnd_send->nextseq, sock->window.wnd_send->base);
            pthread_mutex_unlock(&(sock->send_lock));
            // 改变状态为TIME_WAIT
            sock->state = TIME_WAIT;
            DEBUG_STATE("Socket %p 进入TIME_WAIT状态，持续时间 %d 秒", sock, TIMEWAIT_TIMEOUT);
            // 启动定时器
            start_timer(sock);
        }
        break;
    case CLOSE_WAIT:
        /*
        这个状态的sock不会收到数据包
        */
        DEBUG_STATE("Socket %p 处于CLOSE_WAIT状态", sock);
        break;
    case CLOSING:
        /*
        收到ACK包
        更新接收窗口
        停止计时器，将数据包从未确认链表中移除
        改变状态为TIME_WAIT
        */
        if((flags & ACK_FLAG_MASK)){
            DEBUG_PACKET("收到ACK包（同时关闭情况），sock=%p, ack=%u", sock, ack);
            // 更新接收窗口
            sock->window.wnd_recv->expect_seq = seq + 1;
            DEBUG_DETAIL("更新接收窗口: expect_seq = %u", sock->window.wnd_recv->expect_seq);
            // 停止计时器，将数据包从未确认链表中移除
            stop_timer(sock);
            // 移除已确认的数据包
            pthread_mutex_lock(&(sock->send_lock));
            remove_nacked_packet(sock, ack);
            // 更新发送窗口的base
            sock->window.wnd_send->base = ack;
            pthread_mutex_unlock(&(sock->send_lock));
            DEBUG_DETAIL("更新发送窗口: base = %u", sock->window.wnd_send->base);
            // 改变状态为TIME_WAIT
            sock->state = TIME_WAIT;
            DEBUG_STATE("Socket %p 进入TIME_WAIT状态（同时关闭情况），持续时间 %d 秒", sock, TIMEWAIT_TIMEOUT);
            // 启动定时器
            start_timer(sock);
        }
        break;
    case LAST_ACK:
        /*
        收到ACK包
        关闭连接
        */
        if((flags & ACK_FLAG_MASK)){
            DEBUG_PACKET("收到最终ACK包，完成关闭过程，sock=%p, ack=%u", sock, ack);
            if(ack != sock->window.wnd_send->nextseq){
                DEBUG_STATE("ACK seq错误, expect_seq: %u, ack: %u", sock->window.wnd_send->nextseq, ack);
                return -1;
            }
            // 停止计时器
            stop_timer(sock);
            // 移除已确认的数据包
            pthread_mutex_lock(&(sock->send_lock));
            remove_nacked_packet(sock, ack);
            // 更新发送窗口 - 使用收到的ack值更新base，而不是简单的+1
            sock->window.wnd_send->base = ack;
            pthread_mutex_unlock(&(sock->send_lock));
            DEBUG_DETAIL("更新发送窗口: base = %u", sock->window.wnd_send->base);
            // 更新接收窗口
            pthread_mutex_lock(&(sock->recv_lock));
            sock->window.wnd_recv->expect_seq += 1;
            DEBUG_DETAIL("更新接收窗口: expect_seq = %u", sock->window.wnd_recv->expect_seq);
            pthread_mutex_unlock(&(sock->recv_lock));
            // 关闭连接
            sock->state = CLOSED;
            DEBUG_STATE("Socket %p 已关闭，连接完全终止", sock);
            // 释放资源
            free(sock);
        }
        break;
    case TIME_WAIT:
        /*
        如果收到FIN-ACK包，说明发送的ACK包丢失，重新发送ACK包
        */
        if((flags & FIN_FLAG_MASK) && (flags & ACK_FLAG_MASK)){
            DEBUG_PACKET("收到FIN-ACK包（需要重发ACK），sock=%p, seq=%u, ack=%u", sock, seq, ack);
            if(seq != sock->window.wnd_recv->expect_seq){
                DEBUG_STATE("FIN seq错误, expect_seq: %u, seq: %u", sock->window.wnd_recv->expect_seq, seq);
                return -1;
            }
            // 更新接收窗口
            sock->window.wnd_recv->expect_seq += 1;
            DEBUG_DETAIL("更新接收窗口: expect_seq = %u", sock->window.wnd_recv->expect_seq);
            // 发送ACK包
            pthread_mutex_lock(&(sock->send_lock));
            DEBUG_PACKET("重发ACK包（TIME_WAIT状态）");
            char* msg;
            struct timeval now;
            gettimeofday(&now, NULL);
            msg = create_packet_buf(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
                      DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, ACK_FLAG_MASK, 1, 0, NULL, 0, now);
            sendToLayer3(msg, DEFAULT_HEADER_LEN);
            free(msg);
            // 更新发送窗口 - 这种ACK不需要被确认，所以同步更新base和nextseq
            sock->window.wnd_send->nextseq += 1;
            sock->window.wnd_send->base = sock->window.wnd_send->nextseq; // 同步更新base
            DEBUG_DETAIL("更新发送窗口: nextseq = %u, base = %u", sock->window.wnd_send->nextseq, sock->window.wnd_send->base);
            pthread_mutex_unlock(&(sock->send_lock));
            // 重新启动定时器
            start_timer(sock);
        }
        break;
    case STOP_WAIT:
        /*
        收到ZERO_WINDOW_PROBE-ACK包
        更新rwnd与window_size
        */
        if((flags & ZERO_WINDOW_PROBE_MASK) && (flags & ACK_FLAG_MASK)){
            DEBUG_DETAIL("收到ZERO_WINDOW_PROBE-ACK包，sock=%p, ack=%u", sock, ack);
            // 更新接收窗口
            pthread_mutex_lock(&(sock->send_lock));
            sock->window.wnd_send->rwnd = adv_window;
            TRACE_RWND(sock->window.wnd_send->rwnd);
            sock->window.wnd_send->window_size = sock->window.wnd_send->rwnd < sock->window.wnd_send->cwnd ? sock->window.wnd_send->rwnd : sock->window.wnd_send->cwnd;
            TRACE_SWND(sock->window.wnd_send->window_size);
            DEBUG_DETAIL("更新发送窗口: rwnd = %u, window_size = %u", sock->window.wnd_send->rwnd, sock->window.wnd_send->window_size);
            if(sock->window.wnd_send->nextseq - sock->window.wnd_send->base < sock->window.wnd_send->window_size){
                pthread_cond_signal(&(sock->window.wnd_send->recv_window_not_full));
                sock->state = ESTABLISHED;
                DEBUG_DETAIL("发送窗口非满，唤醒tju_send");
            }
            pthread_mutex_unlock(&(sock->send_lock));
        }
        break;
    default:
        
        break;
    }
    // uint32_t data_len = get_plen(pkt) - DEFAULT_HEADER_LEN;

    // // 把收到的数据放到接受缓冲区
    // while(pthread_mutex_lock(&(sock->recv_lock)) != 0); // 加锁

    // if(sock->received_buf == NULL){
    //     sock->received_buf = malloc(data_len);
    // }else {
    //     sock->received_buf = realloc(sock->received_buf, sock->received_len + data_len);
    // }
    // memcpy(sock->received_buf + sock->received_len, pkt + DEFAULT_HEADER_LEN, data_len);
    // sock->received_len += data_len;

    // pthread_mutex_unlock(&(sock->recv_lock)); // 解锁


    return 0;
}

/*
检查nacked_packet链表是否为空，确定是否有数据包没有被确认
如果有，等待确认
发送FIN包
更新发送窗口
改变状态为FIN_WAIT_1
*/
int tju_close (tju_tcp_t* sock){
    DEBUG_STATE("开始关闭连接，sock=%p，当前状态=%d", sock, sock->state);
    
    //若状态已经不是ESTABLISHED，直接返回
    if(sock->state != ESTABLISHED){
        DEBUG_STATE("socket %p 不在ESTABLISHED状态，关闭操作被跳过", sock);
        return 0;
    }

    // 检查未确认数据包链表是否为空，确定是否有数据包没有被确认
    if(sock->window.wnd_send->head == NULL){
        DEBUG_DETAIL("未确认链表为空，直接发送FIN包");
        // 没有数据包没有被确认，直接发送FIN包
    }else{
        DEBUG_DETAIL("有未确认数据包，等待确认后再关闭");
        // 有数据包没有被确认，等待确认
        while(sock->window.wnd_send->head != NULL){
            // 等待确认
        }
    }
    
    // 发送FIN包
    pthread_mutex_lock(&(sock->send_lock));
    DEBUG_PACKET("发送FIN包，开始四次挥手第一阶段");
    
    // 分配内存，创建包
    struct timeval now;
    gettimeofday(&now, NULL);
    tju_packet_t* packet = create_packet(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
              DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, FIN_FLAG_MASK, 1, 0, NULL, 0, now);
    
    // 使用packet_to_buf转化为字符串并发送
    char* msg = packet_to_buf(packet);
    sendToLayer3(msg, DEFAULT_HEADER_LEN);
    free(msg);
    
    // 将包加入nacked链表 - FIN包需要被确认
    add_nacked_packet(sock, packet);
    
    // 更新发送窗口 - 只更新nextseq，不更新base
    sock->window.wnd_send->nextseq += 1;
    
    // 启动定时器
    start_timer(sock);
    
    pthread_mutex_unlock(&(sock->send_lock));
    
    // 改变状态为FIN_WAIT_1
    sock->state = FIN_WAIT_1;
    DEBUG_STATE("Socket %p 进入FIN_WAIT_1状态", sock);
    
    // 等待状态变为CLOSED
    pthread_mutex_lock(&(sock->state_lock));
    while(sock->state != CLOSED){
        pthread_cond_wait(&(sock->state_change), &(sock->state_lock));
    }
    pthread_mutex_unlock(&(sock->state_lock));

    DEBUG_STATE("连接完全关闭，释放socket %p 资源", sock);
    // 释放资源
    free(sock);
    
    return 0;
}

//全连接与半连接队列相关函数
/*
syn_queue的入队操作（循环队列）
将半连接socket添加到syn队列尾部
返回0表示成功，-1表示队列已满
*/
static int syn_queue_enqueue(tju_tcp_t* sock) {
    DEBUG_DETAIL("将socket %p 添加到SYN队列", sock);
    // 检查队列是否已满
    if (syn_queue.count >= MAX_SOCK) {
        DEBUG_STATE("syn_queue已满，无法入队");
        return -1;
    }
    
    // 在队尾插入元素
    syn_queue.queue[syn_queue.rear] = sock;
    // 更新队尾指针（循环递增）
    syn_queue.rear = (syn_queue.rear + 1) % MAX_SOCK;
    // 更新元素计数
    syn_queue.count++;
    DEBUG_DETAIL("SYN队列入队成功，当前队列长度: %d", syn_queue.count);
    
    return 0;  // 入队成功
}

/*
syn_queue的出队操作（循环队列）
从syn队列头部移除并返回socket
返回出队的socket地址，NULL表示队列为空
*/
static tju_tcp_t* syn_queue_dequeue() {
    // 检查队列是否为空
    if (syn_queue.count == 0) {
        return NULL;  // 队列为空
    }
    
    // 获取队头元素
    tju_tcp_t* sock = syn_queue.queue[syn_queue.front];
    // 清空该位置
    syn_queue.queue[syn_queue.front] = NULL;
    // 更新队头指针（循环递增）
    syn_queue.front = (syn_queue.front + 1) % MAX_SOCK;
    // 更新元素计数
    syn_queue.count--;
    
    return sock;  // 返回出队的socket
}

/*
判断syn_queue是否为空
返回1表示为空，0表示非空
*/
static int syn_queue_is_empty() {
    int is_empty = (syn_queue.count == 0) ? 1 : 0;
    return is_empty;
}

/*
established_queue的入队操作（循环队列）
将已建立连接的socket添加到established队列尾部
返回0表示成功，-1表示队列已满
*/
static int established_queue_enqueue(tju_tcp_t* sock) {
    DEBUG_DETAIL("将socket %p 添加到已建立队列", sock);
    // 检查队列是否已满
    if (established_queue.count >= MAX_SOCK) {
        DEBUG_STATE("established_queue已满，无法入队");
        return -1;
    }
    
    // 在队尾插入元素
    established_queue.queue[established_queue.rear] = sock;
    // 更新队尾指针（循环递增）
    established_queue.rear = (established_queue.rear + 1) % MAX_SOCK;
    // 更新元素计数
    established_queue.count++;
    DEBUG_DETAIL("已建立队列入队成功，当前队列长度: %d", established_queue.count);
    
    // 发送信号通知等待的线程有新连接可用
    pthread_cond_signal(&established_queue_not_empty);
    DEBUG_DETAIL("已通知可能等待的accept()线程处理新连接");
    
    return 0;  // 入队成功
}

/*
established_queue的出队操作（循环队列）
从established队列头部移除并返回socket
返回出队的socket地址，NULL表示队列为空
*/
static tju_tcp_t* established_queue_dequeue() {
    // 检查队列是否为空
    if (established_queue.count == 0) {
        return NULL;  // 队列为空
    }
    
    // 获取队头元素
    tju_tcp_t* sock = established_queue.queue[established_queue.front];
    // 清空该位置
    established_queue.queue[established_queue.front] = NULL;
    // 更新队头指针（循环递增）
    established_queue.front = (established_queue.front + 1) % MAX_SOCK;
    // 更新元素计数
    established_queue.count--;
    
    return sock;  // 返回出队的socket
}

/*
判断established_queue是否为空
返回1表示为空，0表示非空
*/
static int established_queue_is_empty() {
    int is_empty = (established_queue.count == 0) ? 1 : 0;
    return is_empty;
}

//unack_packet链表相关函数
// 创建节点并加入未确认数据包链表
static void add_nacked_packet(tju_tcp_t* sock, tju_packet_t* pkt){
    DEBUG_DETAIL("添加数据包到未确认链表，seq=%u, flags=0x%x, sock=%p", 
                pkt->header.seq_num, pkt->header.flags, sock);
    nacked_packet_t* nack_pkt = malloc(sizeof(nacked_packet_t));
    nack_pkt->pkt = pkt;
    nack_pkt->retransmit_cnt = 0;
    nack_pkt->next = NULL;
    if(sock->window.wnd_send->head == NULL){
        sock->window.wnd_send->head = nack_pkt;
        DEBUG_DETAIL("链表为空，数据包成为链表头");
    }else{
        nacked_packet_t* temp = sock->window.wnd_send->head;
        int count = 1;
        while(temp->next != NULL){
            temp = temp->next;
            count++;
        }
        temp->next = nack_pkt;
        DEBUG_DETAIL("数据包已添加到链表尾部，当前链表长度=%d", count+1);
    }
}
// 移除节点，由于累计确认，移除所有序列号小于ack_seq的节点
static void remove_nacked_packet(tju_tcp_t* sock, uint32_t ack_seq){
    DEBUG_DETAIL("从未确认链表移除已确认数据包，ack_seq=%u, sock=%p", ack_seq, sock);
    if(sock->window.wnd_send->head == NULL){
        DEBUG_DETAIL("未确认链表为空，无需移除");
        return;
    }
    int removed_count = 0;
    // 移除所有序列号小于ack_seq的节点
    while(sock->window.wnd_send->head != NULL && sock->window.wnd_send->head->pkt->header.seq_num < ack_seq){
        DEBUG_DETAIL("移除数据包: seq=%u, flags=0x%x", 
                    sock->window.wnd_send->head->pkt->header.seq_num, 
                    sock->window.wnd_send->head->pkt->header.flags);
        nacked_packet_t* temp = sock->window.wnd_send->head;
        sock->window.wnd_send->head = sock->window.wnd_send->head->next;
        // DEBUG_DETAIL("test: removed successfully");
        // DEBUG_DETAIL("test: update send_time successfully");
        // 释放内存
        free(temp->pkt);
        free(temp);
        removed_count++;
        // DEBUG_DETAIL("测试：循环移除已确认数据包，当前移除次数=%d", removed_count);
    }
    // DEBUG_DETAIL("测试：是否进入死循环");
    if(sock->window.wnd_send->head != NULL){
        DEBUG_DETAIL("共移除 %d 个已确认数据包，当前链表头seq=%u", 
                    removed_count, 
                    sock->window.wnd_send->head->pkt->header.seq_num);
    }else{
        DEBUG_DETAIL("共移除 %d 个已确认数据包，当前链表头为空", removed_count);
    }
}
static void retransmit_nacked_packets(tju_tcp_t* sock){
    pthread_mutex_lock(&(sock->send_lock));
    DEBUG_PACKET("触发快速重传机制，sock=%p", sock);
    if(sock->window.wnd_send->head == NULL){
        DEBUG_DETAIL("未确认链表为空，无需重传");
        pthread_mutex_unlock(&(sock->send_lock));
        return;
    }
    
    stop_timer(sock);

    //更新拥塞控制状态
    sock->window.wnd_send->congestion_status = FAST_RECOVERY;
    sock->window.wnd_send->ssthresh = sock->window.wnd_send->ssthresh / 2 + 3 * MAX_DLEN;
    sock->window.wnd_send->cwnd = sock->window.wnd_send->ssthresh;
    TRACE_CWND(sock->window.wnd_send->congestion_status, sock->window.wnd_send->cwnd);
    sock->window.wnd_send->congestion_status = CONGESTION_AVOIDANCE;
    TRACE_CWND(sock->window.wnd_send->congestion_status, sock->window.wnd_send->cwnd);
    //更新窗口大小
    sock->window.wnd_send->window_size = sock->window.wnd_send->rwnd < sock->window.wnd_send->cwnd ? sock->window.wnd_send->rwnd : sock->window.wnd_send->cwnd;
    TRACE_SWND(sock->window.wnd_send->window_size);
    DEBUG_DETAIL("快速重传: 窗口大小变为 %u", sock->window.wnd_send->window_size);

    nacked_packet_t* temp = sock->window.wnd_send->head;
    
    // 发送数据包
    gettimeofday(&(temp->pkt->sent_time), NULL);
    char *msg = packet_to_buf(temp->pkt);
    sendToLayer3(msg, temp->pkt->header.plen);
    free(msg);
    
    // 重置ack计数
    sock->window.wnd_send->ack_cnt = -5; //防止同一包被反复重传
    
    // 启动定时器
    start_timer(sock);
    
    // 使用DEBUG_PACKET而不是DEBUG_DETAIL来显示重传信息
    DEBUG_PACKET("快速重传: seq=%u, flags=0x%x, 长度=%u", 
            temp->pkt->header.seq_num, 
            temp->pkt->header.flags,
            temp->pkt->header.plen);
    
    pthread_mutex_unlock(&(sock->send_lock));
}

//received_packet链表相关函数
// 创建节点并加入已接收数据包链表
static void add_received_packet(tju_tcp_t* sock, uint32_t seq, uint16_t len, char* data){
    DEBUG_DETAIL("添加乱序数据包到已接收链表，seq=%u, len=%u, sock=%p", seq, len, sock);
    
    received_packet_t* recv_pkt = malloc(sizeof(received_packet_t));
    recv_pkt->seq = seq;
    recv_pkt->len = len;
    recv_pkt->data = malloc(len);
    memcpy(recv_pkt->data, data, len);
    recv_pkt->next = NULL;
    
    if(sock->window.wnd_recv->head == NULL){
        sock->window.wnd_recv->head = recv_pkt;
        DEBUG_DETAIL("链表为空，数据包成为链表头");
    }else{
        //插入合适的位置，如果重复就丢弃
        received_packet_t* temp = sock->window.wnd_recv->head;
        int count = 1;
        while(temp->next != NULL && temp->next->seq < seq){
            temp = temp->next;
            count++;
        }
        
        if(temp->next != NULL && temp->next->seq == seq){
            DEBUG_STATE("检测到重复数据包，seq=%u, 丢弃", seq);
            free(recv_pkt->data);
            free(recv_pkt);
            return;
        }
        
        recv_pkt->next = temp->next;
        temp->next = recv_pkt;
        while(temp->next != NULL){
            temp = temp->next;
            count++;
        }
        DEBUG_DETAIL("数据包已添加到链表中间，当前链表长度=%d", count);
    }
}
// 移除节点，只移除当前节点即可
static void remove_received_packet(tju_tcp_t* sock, uint32_t seq){
    DEBUG_DETAIL("从已接收链表移除已处理数据包，seq=%u, sock=%p", seq, sock);
    if(sock->window.wnd_recv->head == NULL){
        DEBUG_DETAIL("已接收链表为空，无需移除");
        return;
    }
    // 移除当前节点
    if(sock->window.wnd_recv->head->seq == seq){
        DEBUG_DETAIL("移除数据包: seq=%u, len=%u", 
                    sock->window.wnd_recv->head->seq, 
                    sock->window.wnd_recv->head->len);
        received_packet_t* temp = sock->window.wnd_recv->head;
        sock->window.wnd_recv->head = sock->window.wnd_recv->head->next;
        // 释放内存
        free(temp->data);
        free(temp);
        return;
    }
}
    

//计时器相关函数，使用<sys/time.h>中的setitimer函数
/*
超时处理函数
重发未确认链表头的数据包，应当与base指向的序列号一致
如果超过最大重传次数，关闭连接
指数退避：每次重传超时时间加倍
*/
static void timeout_handler(int signum){
    DEBUG_STATE("定时器超时，socket %p, 当前状态 %d", curr_sock, curr_sock->state);
    
    if(curr_sock->state == TIME_WAIT){
        // 关闭连接
        DEBUG_STATE("TIME_WAIT超时，关闭socket %p", curr_sock);
        pthread_mutex_lock(&(curr_sock->state_lock));
        curr_sock->state = CLOSED;
        pthread_mutex_unlock(&(curr_sock->state_lock));
        pthread_cond_signal(&(curr_sock->state_change));
        return;
    }
    
    if(curr_sock->state == STOP_WAIT){
        //重传零窗口探测包
        pthread_mutex_lock(&(curr_sock->send_lock));
        DEBUG_PACKET("零窗口探测超时，重传零窗口探测包");
        struct timeval now;
        gettimeofday(&now, NULL);
        char* packet_buf = create_packet_buf(
            curr_sock->established_local_addr.port,
            curr_sock->established_remote_addr.port,
            curr_sock->window.wnd_send->base,
            curr_sock->window.wnd_recv->expect_seq,
            DEFAULT_HEADER_LEN,
            DEFAULT_HEADER_LEN,
            ZERO_WINDOW_PROBE_MASK,
            1,
            0,
            NULL,
            0,
            now
        );
        sendToLayer3(packet_buf, DEFAULT_HEADER_LEN);
        free(packet_buf);
        // 指数退避：每次重传超时时间加倍
        uint32_t tmp = curr_sock->window.wnd_send->timeout.it_value.tv_usec;
        curr_sock->window.wnd_send->timeout.it_value.tv_sec = curr_sock->window.wnd_send->timeout.it_value.tv_sec * 2 + tmp / 1000000;
        curr_sock->window.wnd_send->timeout.it_value.tv_usec = tmp * 2 % 1000000;
        float rto = curr_sock->window.wnd_send->timeout.it_value.tv_sec * 1000.0 + curr_sock->window.wnd_send->timeout.it_value.tv_usec / 1000.0;
        DEBUG_DETAIL("（零窗口探测报文）应用指数退避，新的超时时间： %.3f ms", 
                     rto);
        pthread_mutex_unlock(&(curr_sock->send_lock));
        return;
    }
    
    pthread_mutex_lock(&(curr_sock->send_lock));
    if(curr_sock->window.wnd_send->head == NULL){
        DEBUG_DETAIL("未确认链表为空，无数据包需重传");
        pthread_mutex_unlock(&(curr_sock->send_lock));
        return;
    }

    // 更新拥塞控制状态
    curr_sock->window.wnd_send->congestion_status = TIMEOUT;
    curr_sock->window.wnd_send->cwnd = MAX_DLEN;
    curr_sock->window.wnd_send->ssthresh /= 2;
    if(curr_sock->window.wnd_send->ssthresh < MAX_DLEN) curr_sock->window.wnd_send->ssthresh = MAX_DLEN;
    TRACE_CWND(curr_sock->window.wnd_send->congestion_status, curr_sock->window.wnd_send->cwnd);
    curr_sock->window.wnd_send->congestion_status = SLOW_START;
    TRACE_CWND(curr_sock->window.wnd_send->congestion_status, curr_sock->window.wnd_send->cwnd);
    // 更新窗口大小
    curr_sock->window.wnd_send->window_size = curr_sock->window.wnd_send->rwnd < curr_sock->window.wnd_send->cwnd ? curr_sock->window.wnd_send->rwnd : curr_sock->window.wnd_send->cwnd; //更新窗口大小
    TRACE_SWND(curr_sock->window.wnd_send->window_size);
    
    // 重发未确认链表头的数据包，应当与base指向的序列号一致
    if(curr_sock->window.wnd_send->head->pkt->header.seq_num != curr_sock->window.wnd_send->base){
        DEBUG_STATE("严重错误：nacked_packet链表维护出错 窗口base: %u, 链表头seq: %u", 
                   curr_sock->window.wnd_send->base, 
                   curr_sock->window.wnd_send->head->pkt->header.seq_num);
        pthread_mutex_unlock(&(curr_sock->send_lock));
        exit(0);
    }
    
    nacked_packet_t* pkt_to_retransmit = curr_sock->window.wnd_send->head;
    if(pkt_to_retransmit->retransmit_cnt > MAX_RETRANSMIT_CNT){
        // 超过最大重传次数，认为数据包丢失，关闭连接
        DEBUG_STATE("超过最大重传次数(%d)，退出进程", MAX_RETRANSMIT_CNT);
        pthread_mutex_unlock(&(curr_sock->send_lock));
        exit(0);
    }

    gettimeofday(&(pkt_to_retransmit->pkt->sent_time), NULL);
    char* packet_buf = packet_to_buf(pkt_to_retransmit->pkt);
    sendToLayer3(packet_buf, pkt_to_retransmit->pkt->header.plen);
    free(packet_buf);
    
    // 更新重传次数
    pkt_to_retransmit->retransmit_cnt += 1;
    
    // 对于控制包使用DEBUG_PACKET，普通数据包使用DEBUG_DETAIL
    if(pkt_to_retransmit->pkt->header.flags & (SYN_FLAG_MASK | FIN_FLAG_MASK)) {
        DEBUG_PACKET("重传控制包：seq=%u, flags=0x%x, 第%d次重传", 
                    pkt_to_retransmit->pkt->header.seq_num, 
                    pkt_to_retransmit->pkt->header.flags, 
                    pkt_to_retransmit->retransmit_cnt);
    } else {
        DEBUG_DETAIL("重传数据包：seq=%u, 长度=%u, 第%d次重传", 
                    pkt_to_retransmit->pkt->header.seq_num, 
                    pkt_to_retransmit->pkt->header.plen,
                    pkt_to_retransmit->retransmit_cnt);
    }
    
    // 指数退避：每次重传超时时间加倍
    // 指数退避：每次重传超时时间加倍
    uint32_t tmp = curr_sock->window.wnd_send->timeout.it_value.tv_usec;
    curr_sock->window.wnd_send->timeout.it_value.tv_sec = curr_sock->window.wnd_send->timeout.it_value.tv_sec * 2 + tmp / 1000000;
    curr_sock->window.wnd_send->timeout.it_value.tv_usec = tmp * 2 % 1000000;
    float rto = curr_sock->window.wnd_send->timeout.it_value.tv_sec * 1000.0 + curr_sock->window.wnd_send->timeout.it_value.tv_usec / 1000.0;
    DEBUG_DETAIL("应用指数退避，新的超时时间： %.3f ms", 
                 rto);
    
    // 重新启动定时器
    start_timer(curr_sock);
    pthread_mutex_unlock(&(curr_sock->send_lock));
}
static void start_timer(tju_tcp_t* sock){
    if(sock->state == TIME_WAIT){
        sock->window.wnd_send->timeout.it_value.tv_sec = TIMEWAIT_TIMEOUT;
        sock->window.wnd_send->timeout.it_value.tv_usec = 0;
        DEBUG_STATE("为socket %p 启动TIME_WAIT定时器，持续时间 %d s", sock, TIMEWAIT_TIMEOUT);
    } else {
        float rto = sock->window.wnd_send->timeout.it_value.tv_sec * 1000.0 + sock->window.wnd_send->timeout.it_value.tv_usec / 1000.0;
        DEBUG_DETAIL("为socket %p 启动定时器，持续时间 %.3f ms", 
                    sock, 
                    rto);
    }
    setitimer(ITIMER_REAL, &sock->window.wnd_send->timeout, NULL);
}
static void stop_timer(tju_tcp_t* sock){
    // 移除过于频繁的定时器停止日志，减少日志量
    // DEBUG_DETAIL("停止socket %p 的定时器", sock);
    struct itimerval zero;
    zero.it_value.tv_sec = 0;
    zero.it_value.tv_usec = 0;
    zero.it_interval.tv_sec = 0;
    zero.it_interval.tv_usec = 0;
    setitimer(ITIMER_REAL, &zero, NULL);
}
static void reset_timer(tju_tcp_t* sock){
    uint32_t rto = sock->window.wnd_send->estimated_rtt > RTO ? sock->window.wnd_send->estimated_rtt : RTO;
    sock->window.wnd_send->timeout.it_value.tv_sec = rto / 1000;
    sock->window.wnd_send->timeout.it_value.tv_usec = rto % 1000 * 1000;
}

// 发送包相关
static void send_ack(tju_tcp_t* sock, struct timeval sent_time){
    char* msg = create_packet_buf(sock->established_local_addr.port, sock->established_remote_addr.port, sock->window.wnd_send->nextseq, sock->window.wnd_recv->expect_seq, 
                        DEFAULT_HEADER_LEN, DEFAULT_HEADER_LEN, ACK_FLAG_MASK, sock->window.wnd_recv->window_size, 0, NULL, 0, sent_time);
    sendToLayer3(msg, DEFAULT_HEADER_LEN);
    free(msg);
    return;
}
